<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input style="width: 240px" v-model="data.name" placeholder="请输入学院名称" :prefix-icon="Search"></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="load">查 询</el-button>
      <el-button type="info" style="margin-left: 10px" @click="reset">重 置</el-button>
    </div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新 增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.collegeList" stripe @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="collegeId" width="150" />
        <el-table-column label="学院名称" prop="name" show-overflow-tooltip />
        <el-table-column label="学院描述" prop="description" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
        <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" circle @click="handleUpdate(scope.row)" />
            <el-button type="danger" :icon="Delete" circle @click="del(scope.row.collegeId)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>

    <el-dialog title="学院信息" v-model="data.formVisible" width="600" destroy-on-close>
      <!-- 合并为一个表单 -->
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px"
        style="padding: 20px 30px 0px 10px">
        <el-form-item label="学院名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入学院名称" />
        </el-form-item>

        <el-form-item label="学院描述" prop="description">
          <el-input v-model="data.form.description" autocomplete="off" placeholder="请输入学院描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>

import { Delete, Edit, Plus, Search } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import alovaInstance from "@/utils/request.js";

const formRef = ref();

const emit = defineEmits(['updateUser'])   // 自定义事件

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  name: '',
  description: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  collegeList: [],
  formVisible: false,
  form: {},
  ids: [],
  rules: {
    name: [
      { required: true, message: '请输入学院名称', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入学院描述', trigger: 'blur' }
    ],
  }
})

const load = () => {
  alovaInstance.Get('/sysAdminCollege/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
    }
  }).then(res => {
    if (res.code === '200') {
      data.collegeList = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
}

//重置输入框操作方法
const reset = () => {
  data.name = ''
  data.description = ''
  //重新渲染数据
  load()
}

//新增操作
const handleAdd = () => {
  //显示新增对话框
  data.formVisible = true
  //防止有脏数据
  data.form = {}
}

//更新（编辑）操作
const handleUpdate = (row) => {
  //深拷贝一个新的对象用于编辑。这样就不会影响行对象
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

//对话框的保存按钮事件
const save = () => {
  formRef.value.validate((valid) => {
    //通过校验才能点击更新或新增的保存操作
    if (valid) {
      //有id进行更新操作。无id进行新增操作
      data.form.collegeId ? update() : add()
    }
  })
}

// 新增（保持不变）
const add = () => {
  console.log("-----data.form:", data.form)
  data.form.createBy = data.user.username
  alovaInstance.Post('/sysAdminCollege/addCollege', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 更新（修复）
const update = () => {
  data.form.updatedBy = data.user.username
  alovaInstance.Put('/sysAdminCollege/updateCollege', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 删除（修改URL路径）
const del = (collegId) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/sysAdminCollege/deleteCollege/${collegId}?updatedBy=${data.user.username}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

// 批量选择（保持不变）
const handleSelectionChange = (rows) => {  //返回选中的行对象数组
  console.log(rows)
  //从选中的行对象中取出所有的id，组成一个新数组！
  //使用map函数(数组内置函数)
  //遍历rows数组，将每个元素（行对象）的id属性值提取出来，组成一个新的数组。并赋值给存储id的数组中
  data.ids = rows.map(row => row.collegeId)
  console.log(data.ids)
}

// 批量删除（修改URL路径）
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选中需删除的数据')
    return
  }
  ElMessageBox.confirm('批量删除数据后无法恢复，您确认删除吗？', '批量删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/sysAdminCollege/deleteCollegeBatch/${data.user.username}`, data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

load()

</script>
